<template>
  <div class="virtual-list" ref="listContainer" @scroll="onScroll">
    <div
      class="virtual-list-item"
      v-for="(item, index) in visibleItems"
      :key="item.id"
      :style="{ height: itemHeight + 'px' }"
    >
      {{ item.name }}
    </div>
  </div>
</template>

<script setup>
import { getFindInfor } from '../../api/index'
import { ref, computed, onMounted ,onUnmounted} from 'vue';

const props = defineProps({
  items: {
    type: Array,
    required: true,
  },
  itemHeight: {
    type: Number,
    default: 30,
  },
});

const listContainer = ref(null);
const startIndex = ref(0);
const visibleCount = ref(0);

// 计算可见项目的数量
const calculateVisibleCount = () => {
  const container = listContainer.value;
  if (container) {
    const containerHeight = container.clientHeight;
    visibleCount.value = Math.ceil(containerHeight / props.itemHeight) + 1;
  }
};

// 计算可见项目的索引范围
const visibleItems = computed(() => {
  const endIndex = startIndex.value + visibleCount.value;
  return props.items.slice(startIndex.value, endIndex);
});

// 滚动处理函数
const onScroll = () => {
  const container = listContainer.value;
  if (container) {
    const scrollTop = container.scrollTop;
    startIndex.value = Math.floor(scrollTop / props.itemHeight);
  }
};

// 组件挂载时计算可见项目数
onMounted(() => {
  calculateVisibleCount();
  window.addEventListener('resize', calculateVisibleCount);
});

// 清理资源
onUnmounted(() => {
  window.removeEventListener('resize', calculateVisibleCount);
});
</script>

<style scoped>
.virtual-list {
  overflow-y: auto;
  height: 400px; /* 设定固定高度 */
  border: 1px solid #ddd;
}

.virtual-list-item {
  box-sizing: border-box;
  border-bottom: 1px solid #f0f0f0;
  line-height: 30px; /* 与 itemHeight 相同 */
  padding: 0 10px;
}
</style>
